package io.geekidea.boot.util.dingtalk;

import cn.hutool.http.HttpStatus;
import com.aliyun.dingtalkhrm_1_0.models.GetEmployeeRosterByFieldResponse;
import com.aliyun.dingtalkhrm_1_0.models.GetEmployeeRosterByFieldResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import java.util.Collections;
import java.util.List;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HrmUtil {

  /**
   * 使用 Token 初始化账号Client
   *
   * @return Client
   * @throws Exception
   */
  public static com.aliyun.dingtalkhrm_1_0.Client createHrmClient() throws Exception {
    com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
    config.protocol = "https";
    config.regionId = "central";
    return new com.aliyun.dingtalkhrm_1_0.Client(config);
  }

  /**
   * 获取员工花名册字段信息 https://open.dingtalk.com/document/orgapp/api-getemployeerosterbyfield
   *
   * @param accessToken
   * @param agentId
   * @param userIdList
   * @return
   */
  public static GetEmployeeRosterByFieldResponseBody listRosters(String accessToken, Long agentId,
      List<String> userIdList,
      List<String> codeList) {
    if (userIdList == null || userIdList.isEmpty() || codeList == null || codeList.isEmpty()) {
      return null;
    }
    if (userIdList.size() > 100) {
      log.error("错误消息：获取员工花名册字段信息,查询用户数量大于100");
      return null;
    }
    com.aliyun.dingtalkhrm_1_0.Client client = null;
    try {
      client = HrmUtil.createHrmClient();
    } catch (Exception e) {
      log.error("错误消息：{}", e.getMessage(), e);
      return null;
    }

    com.aliyun.dingtalkhrm_1_0.models.GetEmployeeRosterByFieldHeaders getEmployeeRosterByFieldHeaders = new com.aliyun.dingtalkhrm_1_0.models.GetEmployeeRosterByFieldHeaders();
    getEmployeeRosterByFieldHeaders.xAcsDingtalkAccessToken = accessToken;
    com.aliyun.dingtalkhrm_1_0.models.GetEmployeeRosterByFieldRequest getEmployeeRosterByFieldRequest = new com.aliyun.dingtalkhrm_1_0.models.GetEmployeeRosterByFieldRequest()
        .setUserIdList(userIdList)
        .setFieldFilterList(codeList)
        .setAppAgentId(agentId)
        .setText2SelectConvert(true);
    try {
      GetEmployeeRosterByFieldResponse resp = client.getEmployeeRosterByFieldWithOptions(
          getEmployeeRosterByFieldRequest, getEmployeeRosterByFieldHeaders, new RuntimeOptions());
      if (resp != null && resp.getStatusCode() == HttpStatus.HTTP_OK && resp.getBody() != null) {
        return resp.getBody();
      }
    } catch (Exception e) {
      log.error("错误消息：{}", e.getMessage(), e);
    }
    return null;
  }
}
